package ss.lianft.tools;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
public class Common {
    private static AuthorizingRealm realm;
    @Autowired
    public void setRealm(AuthorizingRealm realm) {
        Common.realm = realm;
    }

    public static String sha256(String passwd,String salt){
        return new Sha256Hash(passwd,salt).toString();
    }

    public static void flushCurrentAuth(){
        Subject subject = SecurityUtils.getSubject();
        String realmName = subject.getPrincipals().getRealmNames().iterator().next();
        SimplePrincipalCollection principals = new SimplePrincipalCollection(subject.getPrincipal(),realmName);
        subject.runAs(principals);
        realm.getAuthorizationCache().remove(subject.getPrincipals());
        subject.releaseRunAs();
    }

    public static void flushAuth(String username){
        Subject subject = SecurityUtils.getSubject();
        String realmName = subject.getPrincipals().getRealmNames().iterator().next();
        SimplePrincipalCollection principals = new SimplePrincipalCollection(username,realmName);
        subject.runAs(principals);
        realm.getAuthorizationCache().remove(subject.getPrincipals());
        subject.releaseRunAs();
    }
}
